package login_filter

import (
	"errors"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

const UserSessionName = "CurrentUser"

type UserSession struct {
	Id       int64
	Username string
}

func RemoveCurrentUser(c *gin.Context) {
	session := sessions.Default(c)
	session.Delete(UserSessionName)
	_ = session.Save()
}

func SetCurrentUser(c *gin.Context, us UserSession) {
	session := sessions.Default(c)
	session.Set(UserSessionName, us)
	_ = session.Save()
}

func GetCurrentUser(c *gin.Context) (UserSession, error) {
	session := sessions.Default(c)
	currentUser := session.Get(UserSessionName)
	if currentUser == nil {
		return UserSession{}, errors.New("currentUser is nil")
	}
	return currentUser.(UserSession), nil
}

func Authority() func(c *gin.Context) {
	return func(c *gin.Context) {
		user, e := GetCurrentUser(c)
		if e != nil {
			log.Println(e)
			c.Redirect(http.StatusTemporaryRedirect, "/login")
		}
		log.Println(user)
	}
}
